package com.csair.seam.controller.pc;


import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.csair.seam.domain.model.entity.Equip;
import com.csair.seam.domain.model.entity.Inventory;
import com.csair.seam.domain.model.entity.InventoryFeedback;
import com.csair.seam.domain.model.entity.InventoryRecord;
import com.csair.seam.domain.model.entity.LocationTreeNode;
import com.csair.seam.domain.model.entity.SysUser;
import com.csair.seam.domain.model.enums.VisitsModule;
import com.csair.seam.domain.model.param.EquipParam;
import com.csair.seam.domain.model.param.SysUserParam;
import com.csair.seam.domain.model.vo.InventoryDetailVo;
import com.csair.seam.domain.service.IEquipService;
import com.csair.seam.domain.service.IInventoryService;
import com.csair.seam.domain.service.ISysUserService;
import com.csair.seam.infrastructure.log.LogOperation;
import com.csair.seam.infrastructure.log.VisitsLog;
import com.csair.seam.infrastructure.utils.DateHelper;
import com.csair.seam.infrastructure.web.BaseController;
import com.csair.seam.infrastructure.web.BaseResponse;
import com.csair.seam.infrastructure.web.ResponseCode;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "资产盘点接口")
@RestController
@RequestMapping("/pc/inventory")
public class InventoryController extends BaseController {

	@Autowired
    private IEquipService equipService;
	
	@Autowired
    private ISysUserService userService;
	
	@Autowired
	private IInventoryService inventoryService;
    
    @ApiOperation(value = "已盘点列表（分页）", notes = "查询已盘到的资产设备信息数据",httpMethod="POST")
    @PostMapping(value = "/checked")
    @LogOperation(bizName = "查询已盘点数据（pc端）")
//    @VisitsLog(module = VisitsModule.ASSET_INVENTORY)
    @VisitsLog(module = VisitsModule.ASSET_INVENTORY_QUERY)
    public BaseResponse<IPage<Inventory>> getCheckedList(@ApiParam(value = "查询参数")EquipParam param){
        param.setUserCode(getAccount());
        param.setCheckFlag(1);
        return  buildSuccess(inventoryService.findInventoryPage(param));
    }
    
    @ApiOperation(value = "未盘点列表（分页）", notes = "查询未盘到的资产设备信息",httpMethod="POST")
    @PostMapping(value = "/unchecked")
    @LogOperation(bizName = "查询未盘点数据（pc端）")
//    @VisitsLog(module = VisitsModule.ASSET_INVENTORY)
    @VisitsLog(module = VisitsModule.ASSET_INVENTORY_QUERY)
    public BaseResponse<IPage<Inventory>> getUnCheckedList(@ApiParam(value = "查询参数")EquipParam param){
    	param.setUserCode(getAccount());
    	param.setCheckFlag(0);
        return  buildSuccess(inventoryService.findInventoryPage(param));
    }

	@ApiOperation(value = "未盘点列表（分页）", notes = "查询未盘到的资产设备信息",httpMethod="POST")
	@PostMapping(value = "/getUnCheckedListByTotal")
	@LogOperation(bizName = "查询未盘点数据（pc端）")
//    @VisitsLog(module = VisitsModule.ASSET_INVENTORY)
	public BaseResponse<Object> getUnCheckedListByTotal(@ApiParam(value = "查询参数")EquipParam param){
		param.setUserCode(getAccount());
		param.setCheckFlag(0);
		return  buildSuccess(inventoryService.findInventoryPage(param).getTotal());
	}


	@ApiOperation(value = "相符（批量操作）", notes = "资产信息盘点前后相符",httpMethod="POST")
    @PostMapping(value = "/match")
    @LogOperation(bizName = "相符")
    @VisitsLog(module = VisitsModule.ASSET_INVENTORY_MATCH)
    public BaseResponse<Object> match(@ApiParam(value = "表体主键集合") @RequestBody List<String> ids) {
    	List<Inventory> list = inventoryService.findInventoryByIds(ids);
    	if(CollectionUtils.isEmpty(list) || list.size() != ids.size()) {
    		return new BaseResponse<>(ResponseCode.PARAM_ERROR,"参数错误",null);
    	}
    	StringBuilder msg = new StringBuilder();
    	for (Inventory inventory : list) {
        	if(inventory.getBillStatus() != 0) {
        		msg.append("设备【").append(inventory.getEquipName()).append("】非自由态，无法操作;");
        	}
        	if(!getAccount().equals(inventory.getUserCode())) {
        		msg.append("设备【").append(inventory.getEquipName()).append("】当前用户无权操作;");
        	}
        	if("Y".equals(inventory.getIschecked())) {
        		msg.append("设备【").append(inventory.getEquipName()).append("】已盘点，无法操作;");
        	}
        	if(!DateHelper.isFixRange(DateHelper.getCurrentDateTimeStr(), inventory.getStartDate(), inventory.getEndDate())) {
        		msg.append("设备【").append(inventory.getEquipName()).append("】已过盘点时间，无法操作;");
        	}
		}
    	if(msg.length() > 0 ) {
    		return new BaseResponse<>(ResponseCode.ERROR,msg.toString(),null);
    	}
    	
    	InventoryFeedback feedback = new InventoryFeedback();
    	feedback.setIds(ids);
    	
    	SysUser sysUser = userService.queryUserByAccount(getAccount());
    	feedback.setCheckUserName(sysUser.getName());
    	feedback.setCheckDate(DateHelper.getCurrentDateTimeStr());
    	
    	feedback.setMatchFlag(0);
    	inventoryService.updateInventory(feedback);
    	return buildSuccess(null);
    }
    
    @ApiOperation(value = "不符", notes = "资产信息盘点前后不相符",httpMethod="POST")
    @PostMapping(value = "/unmatch")
    @LogOperation(bizName = "不符")
    @VisitsLog(module = VisitsModule.ASSET_INVENTORY_UNMATCH)
    public BaseResponse<Object> unMatch(InventoryFeedback feedback) {
    	if(CollectionUtils.isEmpty(feedback.getIds())) {
    		return new BaseResponse<>(ResponseCode.PARAM_ERROR,"参数错误",null);
    	}
    	Inventory inventory = inventoryService.findInventoryById(feedback.getIds().get(0));
    	if(inventory == null) {
    		return new BaseResponse<>(ResponseCode.PARAM_ERROR,"无效盘点单信息",null);
    	}
    	if(inventory.getBillStatus() != 0) {
    		return new BaseResponse<>(ResponseCode.ERROR,"该设备非自由态，无法操作",null);
    	}
    	String account = getAccount();
    	if(!account.equals(inventory.getUserCode())) {
    		return new BaseResponse<>(ResponseCode.ERROR,"当前用户无权操作该设备",null);
    	}
    	if("Y".equals(inventory.getIschecked())) {
    		return new BaseResponse<>(ResponseCode.ERROR,"该设备已盘点，无法进行此操作",null);
    	}
    	if(!DateHelper.isFixRange(DateHelper.getCurrentDateTimeStr(), inventory.getStartDate(), inventory.getEndDate())) {
    		return new BaseResponse<>(ResponseCode.ERROR,"已过盘点时间，无法操作",null);
    	}
    	
    	if(StringUtils.isNotBlank(feedback.getUserId())) {
    		if(feedback.getUserId().equals(inventory.getUserId())) {
    			return new BaseResponse<>(ResponseCode.ERROR,"现责任人和原责任人不能为同一个人",null);
    		}
    		SysUserParam userParam = new SysUserParam();
        	userParam.setOrgId(inventory.getPkUseDeptBefore());
        	userParam.setUserId(feedback.getUserId());
        	List<SysUser> userList = userService.queryUserByParams(userParam);
    		if(CollectionUtils.isEmpty(userList)) {
    			return new BaseResponse<>(ResponseCode.ERROR,"非同单位人员，无法操作",null);
    		}
    	}
    	
    	if(StringUtils.isNoneBlank(feedback.getLocation()) && feedback.getLocation().equals(inventory.getPkPositionBefore())) {
    		return new BaseResponse<>(ResponseCode.ERROR,"现位置和原位置不能为同位置",null);
    	}
    	
//    	SysUser sysUser = userService.queryUserByAccount(account);
//    	feedback.setCheckUserName(sysUser.getName());
    	feedback.setCheckUserName(inventory.getUserName());
    	feedback.setCheckDate(DateHelper.getCurrentDateTimeStr());
    	
    	feedback.setMatchFlag(1);
    	inventoryService.updateInventory(feedback);
    	return buildSuccess(null);
    }
    
    @ApiOperation(value = "撤回盘点", notes = "对已盘点信息撤回未盘点列表中",httpMethod="POST")
    @PostMapping(value = "/revoke")
    @LogOperation(bizName = "撤回盘点")
    @VisitsLog(module = VisitsModule.ASSET_INVENTORY_REVOKE)
    public BaseResponse<Object> revoke(@RequestParam @ApiParam(value = "表体主键")String id) {
    	Inventory inventory = inventoryService.findInventoryById(id);
    	if(inventory == null) {
    		return new BaseResponse<>(ResponseCode.PARAM_ERROR,"无效盘点单信息",null);
    	}
    	if(inventory.getBillStatus() != 0) {
    		return new BaseResponse<>(ResponseCode.ERROR,"该设备非自由态，无法操作",null);
    	}
    	if(!getAccount().equals(inventory.getUserCode())) {
    		return new BaseResponse<>(ResponseCode.ERROR,"当前用户无权操作该设备",null);
    	}
    	if(!DateHelper.isFixRange(DateHelper.getCurrentDateTimeStr(), inventory.getStartDate(), inventory.getEndDate())) {
    		return new BaseResponse<>(ResponseCode.ERROR,"已过盘点时间，无法操作",null);
    	}
    	inventoryService.updateRevoke(id);
    	return buildSuccess(null);
    }
    
    @ApiOperation(value = "盘点详情", notes = "获取盘点详情信息",httpMethod="POST")
    @PostMapping(value = "/detail")
    @LogOperation(bizName = "查询盘点详情（pc端）")
    public BaseResponse<InventoryDetailVo> detail(@RequestParam @ApiParam(value = "表体主键")String id) {
    	//盘点单信息
    	Inventory inventory = inventoryService.findInventoryById(id);
    	if(inventory == null) {
    		return new BaseResponse<>(ResponseCode.PARAM_ERROR,"参数错误",null);
    	}
    	//设备详细信息
    	Equip equip = equipService.findEquipByCode(inventory.getEquipCode());
    	if(equip == null) {
    		return new BaseResponse<>(ResponseCode.PARAM_ERROR,"参数错误",null);
    	}
    	if(!getAccount().equals(equip.getUserCode())) {
    		return new BaseResponse<>(ResponseCode.ERROR,"当前用户无权查看该设备",null);
    	}
    	//盘点记录
    	EquipParam param = new EquipParam();
    	param.setUserCode(getAccount());
    	param.setCode(inventory.getEquipCode());
    	List<InventoryRecord> inventoryRecordList = inventoryService.findInventoryRecord(param);
    	
    	return buildSuccess(new InventoryDetailVo(inventory, equip, inventoryRecordList));
    }
    
    @ApiOperation(value = "获取本单位责任人", notes = "getOrgAssetUser",httpMethod="POST")
    @PostMapping(value = "/getOrgAssetUser")
    public BaseResponse<List<SysUser>> getOrgAssetUser(SysUserParam param) {
    	return buildSuccess(userService.queryUserByParams(param));
    }
    
    @ApiOperation(value = "获取指定位置的子列表", notes = "getChildrenLocation",httpMethod="GET")
    @GetMapping(value = "/getChildrenLocation")
    public BaseResponse<List<LocationTreeNode>> getChildrenLocation(@RequestParam(defaultValue = "~") @ApiParam("父位置id")String fk) {
//    	return buildSuccess(inventoryService.findLocationNodeList(fk));
    	return buildSuccess(inventoryService.findLocationTree(fk));
    }

}

